﻿using Hx.ADSyncPlatform.WebApi.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.IO;
using System.Linq;
using System.Net;

namespace Hx.ADSyncPlatform.Filter
{
    public class ValidModelStateFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {

            var requestReader = new StreamReader(context.HttpContext.Request.Body);
            string requestContent = requestReader.ReadToEndAsync().Result;
            if (!context.ModelState.IsValid)
            {
                //获取验证失败的模型字段
                var errors = context.ModelState
                    .Where(e => e.Value.Errors.Count > 0)
                    .Select(e => e.Value.Errors.First().ErrorMessage)
                    .ToList();

                var str = string.Join("|", errors);

                var json = new Result<string>()
                {
                    status = 500,
                    msg = str,
                    data = str,
                    success = false

                };
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
                context.Result = new BadRequestObjectResult(json);
            }

        }
    }
}
